/* eslint-disable @typescript-eslint/no-unused-vars */
import { Device, GatewayType } from "@/api/interface/iot";
import { getGateway, saveToProduct, syncGateway, syncGetGateway } from "@/api/modules/iot/gateway";
import { getProfile } from "@/api/modules/model/profile";
import { getSchema } from "@/api/modules/model/schema";
import { serviceStart, serviceStop } from "@/api/modules/service/service";
import PageHeader from "@/components/Frame/PageHeader";
import { SchemaItem } from "@/components/JsonSchemaForm/interface";
import BasicInfo from "@/components/Sansan/Model/components/BasicInfo";
import RunningLog from "@/components/Sansan/Model/components/RunningLog.vue";
import JsonView from "@/components/Sansan/Model/develop/PrviewSchemaJson";
import SensorList from "@/components/Sansan/Model/device/SensorFormList";
import GatewayConfig from "@/components/Sansan/Model/gateway/GatewayConfig";
import Navigation from "@/components/Sansan/Model/gateway/Navigation";
import SimpleInfo from "@/components/Sansan/Model/gateway/SimpleInfo";
import ExtLower from "@/components/Sansan/Model/gateway/extLower";
import OnlineStatus from "@/components/Sansan/Status/OnlineStatus";
import { MessageType } from "@/enums/messageEnum";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import router from "@/routers";
import { IotStore } from "@/stores/modules/iot";
import { PublicStore } from "@/stores/modules/public";
import { AuthBtns, SchemaNodeKey } from "@/utils/constants";
import mittBus from "@/utils/mittBus";
import { showMsg, showTips } from "@/utils/util";
import { useRoute } from "vue-router";
import SaveToProduct from "../product/components/SaveToProduct";
import BasicDialog from "./components/basicInfo/basicDialog";
import UploadDialog from "./components/basicInfo/uploadDialog";
import { ComponentInternalInstance, getCurrentInstance } from "vue";
import { isRootDeptId } from "@/utils/format";
import FuncList from "@/components/Sansan/Model/device/FuncList";
import EventLog from "../device/protocol/components/eventLog";
import DialogBox from "@/components/DialogBox";
export default defineComponent({
	setup() {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		const route = useRoute();
		const publicStore = PublicStore();
		const iotStore = IotStore();
		let type = (route.query.type as GatewayType) || GatewayType.SoftGateway;
		// const schemaInfo = ref<SchemaItem>({});
		let menuId = route.query.menuId || GatewayType.SoftGateway;
		const gatewaySchemaInfo = ref<SchemaItem>({});
		provide(SchemaNodeKey.schema, gatewaySchemaInfo);
		provide(SchemaNodeKey.gatewaySchema, gatewaySchemaInfo);
		// const prifileInfo = ref<any>({});
		const gatewayPrifileInfo = ref<any>({});
		provide(SchemaNodeKey.profile, gatewayPrifileInfo);
		provide(SchemaNodeKey.gatewayProfile, gatewayPrifileInfo);
		const detail = reactive<any>({ detail: {} });
		provide(SchemaNodeKey.detailInfo, detail);
		const disabledMod = ref(true);
		provide(AuthBtns.disabledMod, disabledMod);
		mittBus.on("refreshGatewayDetail", () => {
			init();
		});
		onBeforeUnmount(() => {
			mittBus.off("refreshGatewayDetail");
		});
		const buttonsList = ref<any>([]);
		onMounted(async () => {
			init();
			// 获取页面按钮权限
			buttonsList.value = await useAuthButtons((menuId as string).replaceAll("_", "-"));
			disabledMod.value =
				!!isRootDeptId([detail.detail]) || !buttonsList.value.some((item: any) => item.path == AuthBtns.pathMod);
		});
		const init = async () => {
			await initIotData();
			// initProfile();
			// initSchema();
			await initGatewayProfile();
			await initGatewaySchema();
			// type == GatewayType.SoftGateway && (await initServiceDetail());
		};
		// const initServiceDetail = async () => {
		// 	let { result, code } = await serviceDetail({ instanceId: `${detail.detail.sn}.${detail.detail.sn}.SSIOT-MASTER` });
		// 	if (code == 200) {
		// 		detail.detail.bin = result.bin;
		// 		detail.detail.arg = result.arg;
		// 		detail.detail.path = result.path;
		// 		detail.detail.version = result.version;
		// 	}
		// };
		//初始化设备信息
		const initIotData = async () => {
			let { result, code } = await getGateway({ idSn: route.query.sn as string }, type);
			if (code == 200) {
				detail.detail = result;
				detail.detail.location = detail.detail.location || {};
			} else {
				showMsg("未找到相关数据", MessageType.error);
				if (window.frames.length != parent.frames.length) return;
				timeOut.value = setTimeout(() => {
					router.go(-1);
				}, 3000);
			}
		};
		//未找到设备数据时三秒后返回上级页面
		let timeOut = ref();
		//销毁定时器
		onBeforeUnmount(() => {
			clearInterval(timeOut.value);
			timeOut.value = "";
		});
		// const initSchema = async () => {
		// 	const { result } = await getSchema({ sn: route.query.sn });
		// 	schemaInfo.value = result.schema;
		// };
		// const initProfile = async () => {
		// 	const { result } = await getProfile({ idSn: route.query.sn });
		// 	prifileInfo.value = result;
		// };
		const initGatewaySchema = async () => {
			const { result } = await getSchema({ sn: detail.detail.sn });
			gatewaySchemaInfo.value = result.schema;
		};
		const initGatewayProfile = async () => {
			const { result } = await getProfile({
				idSn: detail.detail.sn
			});
			gatewayPrifileInfo.value = result;
		};

		const currNav = ref<string>("");
		const basicDialog = reactive({
			title: proxy?.$t("gateway_detail.dialog_title.modify"),
			visible: false
		});
		const changeNav = (nav: string) => {
			currNav.value = nav;
		};
		const detailDialog = reactive<any>({
			title: proxy?.$t("gateway_detail.dialog_title.edit"),
			detail: {},
			visible: false
		});
		const submitBasic = async () => {
			detailDialog.visible = false;
			//和列表的添加公用一个弹框，弹框添加成功后返回
			initIotData();
		};
		//上传网关程序
		const uploadParam = reactive({
			data: { instanceId: "" },
			headers: { Authentication: "" }
		});
		const beforeUpload = () => {
			uploadParam.data.instanceId = `${detail.detail.sn}.${detail.detail.sn}.SSIOT-MASTER`;
			uploadParam.headers.Authentication = publicStore.token;
			return true;
		};
		const uploadGatewaySuccess = async (res: any) => {
			let { code, message } = res;
			showTips(code, proxy?.$t("gateway_detail.tips.update"), message);
		};
		const uploadGatewayError = async () => {
			showMsg(proxy?.$t("gateway_detail.msg.updatefail"), false);
		};
		//停止、启动网关
		const operateGateway = async (type: string) => {
			let res;
			if (type == "start") {
				res = await serviceStart({ instanceId: `${detail.detail.sn}.${detail.detail.sn}.SSIOT-MASTER` });
			} else {
				res = await serviceStop({ instanceId: `${detail.detail.sn}.${detail.detail.sn}.SSIOT-MASTER` });
			}
			let ok = showTips(
				res.code,
				type == "start" ? proxy?.$t("gateway_detail.tips.start") : proxy?.$t("gateway_detail.tips.stop"),
				res.message
			);
			if (ok) {
				setTimeout(async () => {
					await init();
				}, 1000);
			}
		};

		//按钮事件
		const handleFn = function (fn: String, row?: any) {
			switch (fn) {
				case "saveToProduct":
					saveToProductDialog.formData.id = detail.detail.sn;
					saveToProductDialog.formData.name = detail.detail.name;
					saveToProductDialog.formData.type = detail.detail.type;
					saveToProductDialog.visible = true;
					break;
				case "sync":
					syncGateway({ idSn: detail.detail.sn }, detail.detail.type).then(res => {
						showTips(res.code, proxy?.$t("gateway_detail.tips.sync"), res.message);
					});
					break;
				case "syncGet":
					syncGetGateway({ idSn: detail.detail.sn }).then(res => {
						showTips(res.code, proxy?.$t("gateway_detail.tips.sync_get"), res.message);
						init();
					});
					break;
				case "eventLog":
					eventLogVisible.value = true;
					break;
			}
		};
		const saveToProductDialog = reactive<any>({
			visible: false,
			formData: {
				id: "",
				name: "",
				type: GatewayType.Device
			}
		});

		const submitToProduct = async (data: Device.ReqProduct) => {
			data.idSn = data.id;
			let { code, message } = await saveToProduct(data, data.deviceType);
			let ok = showTips(code, proxy?.$t("gateway_detail.tips.save"), message);
			if (ok) saveToProductDialog.visible = false;
		};
		const uploadDialog = reactive<any>({
			title: proxy?.$t("gateway_detail.dialog_title.upload"),
			visible: false
		});
		const eventLogVisible = ref(false);
		return () => {
			return (
				<div class="">
					<DialogBox v-model:visible={eventLogVisible.value} width={"80%"} title="事件日志" hideFooter>
						<EventLog detail={detail.detail} />
					</DialogBox>
					<UploadDialog
						width="700px"
						title={uploadDialog.title}
						v-model:visible={uploadDialog.visible}
						detail={detail.detail}
						onSubmit={() => {
							init();
							uploadDialog.visible = false;
						}}
					></UploadDialog>
					<PageHeader
						showBackText={false}
						v-slots={{
							operate: () => {
								return (
									<>
										<el-button class="iconfont iconfile-text" onClick={() => handleFn("eventLog", detail.detail)}>
											事件日志
										</el-button>
										{buttonsList.value
											.filter(
												(item: any) =>
													item.path != AuthBtns.pathMod &&
													item.path != AuthBtns.pathDel &&
													item.path != AuthBtns.pathAdd &&
													item.path != AuthBtns.pathUpdateLocation &&
													item.path != AuthBtns.pathAssignGroup
											)
											.map((item: any) => {
												return (
													<>
														{item.path == "start" ? (
															<el-button class="iconfont iconbx-skip-next-circle" onClick={() => operateGateway(item.path)}>
																{item.menuName}
															</el-button>
														) : item.path == "stop" ? (
															<el-button class="iconfont iconbx-stop-circle mr-1" onClick={() => operateGateway(item.path)}>
																{item.menuName}
															</el-button>
														) : item.path == "upgrade" ? (
															<el-button
																class="iconfont iconbx-upload"
																onClick={() => {
																	uploadDialog.visible = true;
																}}
															>
																{item.menuName}
															</el-button>
														) : (
															<el-button
																class="iconfont iconbx-skip-next-circle"
																onClick={() => handleFn(item.path, detail.detail)}
															>
																{item.menuName}
															</el-button>
														)}
													</>
												);
											})}
										{!disabledMod.value && (
											<el-button
												type="primary"
												onClick={() => {
													detailDialog.detail = { ...detail.detail };
													detailDialog.visible = true;
												}}
											>
												{proxy?.$t("gateway_detail.btn.edit")}
											</el-button>
										)}
									</>
								);
							}
						}}
					>
						<div>
							<div>{detail.detail.name || "--"}</div>
							<div class="font-thin text-sm">SN：{detail.detail.sn}</div>
						</div>
						<OnlineStatus class="ml-4 mr-4" v-model={detail.detail.onlineStatus} />
						<el-link class="iconfont iconbx-sync ml-2" type="primary" onClick={init}>
							{proxy?.$t("gateway_detail.btn.refresh")}
						</el-link>
					</PageHeader>

					<SaveToProduct
						title={proxy?.$t("gateway_detail.dialog_title.save")}
						v-model:visible={saveToProductDialog.visible}
						formData={saveToProductDialog.formData}
						onSubmit={(data: Device.ReqProduct) => {
							submitToProduct(data);
						}}
					></SaveToProduct>

					<BasicDialog
						width="700px"
						title={detailDialog.title}
						v-model:visible={detailDialog.visible}
						detail={detailDialog.detail}
						onSubmit={submitBasic}
					></BasicDialog>

					{Object.keys(gatewaySchemaInfo.value).length ? (
						<>
							<div class="iot-detail-content">
								{/* 导航分类：基本信息、设备参数、设备模型、设备日志 */}
								<Navigation onChange={val => changeNav(val)} />

								<div class="bg-white detail-type-detail">
									{/*基本信息*/}
									{currNav.value == SchemaNodeKey.basic ? <BasicInfo type={GatewayType.Gateway} /> : null}
									{/*网关	配置*/}
									{currNav.value == SchemaNodeKey.extNavGatewayConfig ? <GatewayConfig /> : null}
									{/*设备配置信息--接入地址、接入端口*/}
									{/* {currNav.value == SchemaNodeKey.extNavDeviceConfig ? <DeviceConfig /> : null} */}
									{/*设备变量配置--变量字段描述*/}
									{/* {currNav.value == SchemaNodeKey.extNavSensorConfig ? <SensorConfig /> : null} */}
									{/* 下位机 */}
									{currNav.value == SchemaNodeKey.extLower ? <ExtLower /> : null}
									{/*设备模型*/}
									{currNav.value == SchemaNodeKey.sensor ? <SensorList /> : null}
									{/* 控制功能 */}
									{currNav.value == SchemaNodeKey.funcs ? <FuncList /> : null}
									{/*运行日志*/}
									{/* {currNav.value == SchemaNodeKey.extRunningLog ? (
										<RunningLog class="pt-4" instanceId={`${detail.detail.sn}.${detail.detail.sn}.SSIOT-MASTER`} />
									) : null} */}
									{/*模型定义*/}
									{currNav.value == SchemaNodeKey.extDevelop ? <JsonView type={GatewayType.Gateway} /> : null}
								</div>
							</div>
						</>
					) : (
						""
					)}
				</div>
			);
		};
	}
});
